package top.duduwy.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.duduwy.model.RegionStats;
import top.duduwy.service.DataService;

import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class DataController {

    @Autowired
    DataService dataService;

    @GetMapping("/")
    public String data(Model model, String country) throws IOException {
        List<RegionStats> list = dataService.fetchAllData();
        // 根据 国家名称、省份名称 排序
        list.sort(null);

        //传了country参数, 把符合条件的筛选出来
        if (country != null) {
            list = list.stream()
                    .filter(region -> region.getCountry()
                            .toLowerCase()
                            .contains(country.toLowerCase()))
                    .collect(Collectors.toList());
        }
        int total = list.stream().mapToInt(RegionStats::getLatestTotalCases).sum();
        int addTotal = list.stream().mapToInt(RegionStats::getLatestTotalCases).sum();

        model.addAttribute("totalCase",total);
        model.addAttribute("addTotal",addTotal);
        model.addAttribute("time", LocalDate.now());
        model.addAttribute("regionList", list);

        return "index";
    }
}
